﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Admin.Core.Middlewares/SwaggerBasicAuthMiddleware 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       SwaggerBasicAuthMiddleware
* 创建时间：  2025/5/23 18:54:35
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.AspNetCore.Http;
using SSPivot.Common.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace SSPivot.Admin.Core.Middlewares
{
    /// <summary>
    /// Swagger授权登录拦截
    /// </summary>
    public class SwaggerBasicAuthMiddleware
    {
        private readonly RequestDelegate next;
        private readonly IConfiguration _configuration;
        public SwaggerBasicAuthMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _configuration = configuration;
            this.next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            var path = "/" + _configuration.GetSection("Swagger").GetValue<string>("routePrefix");// ConfigHelper.GetContent("SwaggerConfig", "routePrefix");

            if (context.Request.Path.StartsWithSegments(path))
            {
                string authHeader = context.Request.Headers["Authorization"];
                if (authHeader != null && authHeader.StartsWith("Basic "))
                {
                    // Get the credentials from request header
                    var header = AuthenticationHeaderValue.Parse(authHeader);
                    var inBytes = Convert.FromBase64String(header.Parameter);
                    var credentials = Encoding.UTF8.GetString(inBytes).Split(':');
                    var username = credentials[0];
                    var password = credentials[1];

                    var swaggerUserName = _configuration.GetSection("Swagger").GetValue<string>("username");// ConfigHelper.GetContent("SwaggerConfig", "username");
                    var swaggerPassWord = _configuration.GetSection("Swagger").GetValue<string>("password");// ConfigHelper.GetContent("SwaggerConfig", "password");

                    // validate credentials
                    if (!string.IsNullOrEmpty(swaggerUserName) && !string.IsNullOrEmpty(swaggerPassWord) && username.Equals(swaggerUserName) && password.Equals(swaggerPassWord))
                    {
                        await next.Invoke(context).ConfigureAwait(false);
                        return;
                    }
                }
                context.Response.Headers["WWW-Authenticate"] = "Basic";
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                await next.Invoke(context).ConfigureAwait(false);
            }
        }



    }
}
